class PageLoader {
    constructor() {
        this.loader = document.getElementById('global-loader');
        if (!this.loader) {
            console.error('Loader element not found!');
            return;
        }

        this._initRealtime().then(() => {
            this._bindEvents();
            console.debug('[LightTheme] Loader initialized');
        });
    }

    async _initRealtime() {
        // 等待frappe.realtime可用
        let attempts = 0;
        while (!frappe.realtime?.trigger && attempts++ < 5) {
            await new Promise(r => setTimeout(r, 300));
        }
        
        if (!frappe.realtime) {
            frappe.realtime = { on: () => {}, trigger: () => {} };
            console.warn('Realtime service not available, using fallback');
        }
    }

    _bindEvents() {
        // 主加载事件
        frappe.realtime.on('global_loading', (state) => {
            state ? this.show() : this.hide();
        });

        // 降级方案：直接监听DOM事件
        document.addEventListener('page-load-start', () => this.show());
        document.addEventListener('page-load-end', () => this.hide());
    }

    show() {
        this.loader?.classList.add('active');
    }

    hide() {
        this.loader?.classList.remove('active');
    }
}

// 安全初始化
frappe.ready(() => {
    if (frappe.boot.theme?.enable_page_loader !== 0) {
        window._page_loader = new PageLoader();
    }
});